package com.aiolos.wxdc.aspect;

import com.aiolos.wxdc.constant.CookieConstant;
import com.aiolos.wxdc.exception.SellerAuthorizeException;
import com.aiolos.wxdc.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 卖家端系统身份验证AOP
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    /**
     * 定义将要拦截的切入点：拦截那些url进行身份验证
     */
    //拦截com.aiolos.wxdc.controller包下以Aop开头的Controller中的所有public方法
    //并且不拦截com.aiolos.wxdc.controller包下AopLoginController中的所有public方法
    @Pointcut("execution(public * com.aiolos.wxdc.controller.Aop*.*(..))"+
            "&& !execution(public * com.aiolos.wxdc.controller.AopLoginController.*(..))")
    public void verify(){}

    /**
     *  在切入点之前，执行该方法进行身份验证
     */
    @Before("verify()")
    public void doVerify(){
        //1. 获取HttpServletRequest
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //2. 获取cookie，并与redis中的进行比对
        Cookie cookie = CookieUtils.get(request, CookieConstant.TOKEN);
        if(cookie == null){
            //没有登录
            log.info("[登录校验] cookie中查询不到token");
            throw new SellerAuthorizeException();
        }
        //3. 到redis中查询cookie中的token是否存在
        String tokenValue = null;//从redis中查询
        if(StringUtils.isEmpty(tokenValue)){
            log.info("[登录校验] redis中查询不到token");
            throw new SellerAuthorizeException();
        }
    }
}
